package com.xie.authority_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xie.authority_system.dao.PermissionMapper;
import com.xie.authority_system.entity.Permission;
import com.xie.authority_system.entity.User;
import com.xie.authority_system.service.PermissionService;
import com.xie.authority_system.service.UserService;
import com.xie.authority_system.utils.MenuTree;
import com.xie.authority_system.vo.RolePermissionVo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * @author XIEJINGCHENG
 * @description 针对表【sys_permission(权限表)】的数据库操作Service实现
 * @createDate 2024-01-08 14:45:18
 */
@Service
@Transactional
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission>
        implements PermissionService {

    @Resource
    private UserService userService;

    @Override
    public List<Permission> findPermissionListByUserId(Long userId) {
        return baseMapper.findPermissionListByUserId(userId);
    }

    @Override
    public List<Permission> findPermissionList() {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("order_num");
        List<Permission> permissionList = baseMapper.selectList(queryWrapper);
        List<Permission> menuTree = MenuTree.makeMenuTree(permissionList, 0L);
        return menuTree;
    }

    @Override
    public boolean hasChildrenOfPermission(Long id) {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(!ObjectUtils.isEmpty(id), "parent_id", id);
        if (baseMapper.selectCount(queryWrapper) > 0) {
            return true;
        }
        return false;
    }

    @Override
    public List<Permission> findParentPermissionList() {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("type", Arrays.asList(0, 1));
        queryWrapper.orderByAsc("order_num");
        List<Permission> permissionList = baseMapper.selectList(queryWrapper);
        Permission permission = new Permission();
        permission.setId(0L);
        permission.setParentId(-1L);
        permission.setLabel("顶级菜单");
        permission.setOrderNum(-1);
        permissionList.add(permission);

        List<Permission> menuTree = MenuTree.makeMenuTree(permissionList, -1L);
        return menuTree;
    }

    @Override
    public RolePermissionVo findPermissionTree(Long userId, Long roleId) {
        // 查找用户
        User user = userService.getById(userId);
        List<Permission> list = null;

        // 如果是管理员则查找所有的权限列表, 否则只查询该用户的权限列表
        if (!ObjectUtils.isEmpty(user) && user.getIsAdmin() == 1) {
            list = baseMapper.selectList(null);
        } else {
            list = baseMapper.findPermissionListByUserId(userId);
        }

        // 创建菜单树
        List<Permission> permissionList = MenuTree.makeMenuTree(list, 0L);

        // 查询该角色对应的权限列表
        List<Permission> rolePermissions = baseMapper.findPermissionListByRoleId(roleId);

        List<Long> listIds = new ArrayList<>();

        Optional.ofNullable(list).orElse(new ArrayList<>())
                .stream()
                .filter(item -> item != null)
                .forEach(item -> {
                    Optional.ofNullable(rolePermissions).orElse(new ArrayList<>())
                            .stream()
                            .filter(Objects::nonNull)
                            .forEach(obj -> {
                                // 如果用户下的权限id 等于 角色下的权限id, 则将该权限id加入原有权限列表中
                                if (item.getId().equals(obj.getId())) {
                                    listIds.add(obj.getId());
                                    return;
                                }
                            });
                });

        RolePermissionVo vo = new RolePermissionVo();
        // 权限列表
        vo.setPermissionList(permissionList);
        // 原有权限列表
        vo.setCheckList(listIds.toArray());

        return vo;
    }
}
